package com.yuanduan.mplus.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.cj.framework.app.BaseActivity;
import com.cj.framework.app.BaseApplication;
import com.cj.framework.util.IOkHttp;
import com.cj.framework.util.Msg;
import com.cj.framework.util.OkHttpImp;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.db.dao.UserDao;
import com.yuanduan.mplus.db.entity.User;
import com.yuanduan.mplus.model.entity.RS;
import com.yuanduan.mplus.util.FileImageUpload;

import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 提交驾驶证（个人设置页面的认证）
 */
public class InsureActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_submit;
    private ImageButton ib_back;
    private EditText et_identity;
    private ImageView iv_front;
    private ImageView iv_back;

    private IOkHttp okHttp=new OkHttpImp();
    private IOkHttp.IHttpCallback callback=new IOkHttp.IHttpCallback() {
        @Override
        public void onResponse(Msg msg, int index) {
            String message=msg.content();
            RS rs= (RS) Config.decry(message,RS.class);
            switch (index){
                case 0:
                    if(rs.getRs()==1){
                        dialog.setMessage("提交审核...");
                        Toast.makeText(InsureActivity.this,"更新身份证号码成功",Toast.LENGTH_SHORT).show();
                        HashMap<String,String> hashMap=new HashMap();
                        hashMap.put("UserPhone",user.getUserPhone());
                        hashMap.put("UserPassword",user.getUserPwd());
                        okHttp.httpInfoPost(Config.URL+Config.APPLYIDCARD,Config.translateMap(hashMap),callback,1);
                    }else{
                        Toast.makeText(InsureActivity.this,"更新身份证号码失败",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 1:
                    if(rs.getRs()==1){
                        dialog.dismiss();
                        Toast.makeText(InsureActivity.this,"提交审核成功",Toast.LENGTH_SHORT).show();
                        updateUserInfo();
                    }else{
                        dialog.dismiss();
                        Toast.makeText(InsureActivity.this,"提交审核失败",Toast.LENGTH_SHORT).show();
                    }
                    break;
            }

        }

        @Override
        public void onError(Exception e) {
            Toast.makeText(InsureActivity.this,"网络出错",Toast.LENGTH_SHORT).show();
        }
    };

    private void updateUserInfo() {
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("UserPhone",user.getUserPhone());
        hashMap.put("UserPassword",user.getUserPwd());
        hashMap.put("TargetUserPhone",user.getUserPhone());
        okHttp.httpInfoPost(Config.URL + Config.USERINFO, Config.translateMap(hashMap), new IOkHttp.IHttpCallback() {
            @Override
            public void onResponse(Msg msg, int index) {
                String message=msg.content();
                User user1= (User) Config.decry(message,User.class);
                user1.setUserPwd(user.getUserPwd());
                user1.set_id(user.get_id());
                userDao.update(user1);
            }

            @Override
            public void onError(Exception e) {

            }
        });
    }

    private ProgressDialog dialog;
    private static final  int CAPTURE_IMAGE=10;
    private static final int GALLERY_IMAGE=11;
    private int state;

    private UserDao userDao;
    private User user;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            dialog.dismiss();
            switch (msg.what){
                case 0:
                    if(state==0){
                        Toast.makeText(InsureActivity.this,"上传身份证正面成功",Toast.LENGTH_SHORT).show();
                        Glide.with(InsureActivity.this)
                                .load(mFilePath)
                                .asBitmap()
                                .override(iv_front.getWidth(),iv_front.getHeight())
                                .into(iv_front);
                    }else{
                        Toast.makeText(InsureActivity.this,"上传身份证反面成功",Toast.LENGTH_SHORT).show();
                        Glide.with(InsureActivity.this)
                                .load(mFilePath)
                                .asBitmap()
                                .into(iv_back);
                    }
                    break;
                case 1:
                    Toast.makeText(InsureActivity.this,"上传失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private FileImageUpload.ImageCallback imageCallback=new FileImageUpload.ImageCallback() {
        @Override
        public void onFail() {
            handler.sendEmptyMessage(1);
        }

        @Override
        public void onSuccess() {
            handler.sendEmptyMessage(0);
        }
    };



    @Override
    protected void findId() {
        tv_submit= (TextView) findViewById(R.id.ownerinsure_tv_submit);
        et_identity= (EditText) findViewById(R.id.ownerinsure_et_identityNum);
        ib_back= (ImageButton) findViewById(R.id.ownerinsure_ib_back);
        iv_back= (ImageView) findViewById(R.id.ownerinsure_iv_identityBack);
        iv_front= (ImageView) findViewById(R.id.ownerinsure_iv_identityFront);
    }

    @Override
    protected void logic() {
        dealwithUrlAndIdentity();

        userDao= BaseApplication.getDaoSession().getUserDao();
        List list=userDao.queryBuilder().list();
        user= (User) list.get(0);
        dialog=new ProgressDialog(this);

        ib_back.setOnClickListener(this);
        iv_front.setOnClickListener(this);
        tv_submit.setOnClickListener(this);
        iv_back.setOnClickListener(this);
    }

    //处理前置初始化
    private void dealwithUrlAndIdentity() {
        if((PersonalSetting.num_identity!=null)&&(!PersonalSetting.num_identity.equals(""))){  //处理身份证号码
            et_identity.setText(PersonalSetting.num_identity);
        }

        if((PersonalSetting.url_front!=null)&&(!PersonalSetting.url_front.equals(""))){  //身份证前照片
            Glide.with(this)
                    .load(Config.URL+PersonalSetting.url_front)
                    .asBitmap()
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(iv_front);
        }

        if((PersonalSetting.url_back!=null)&&(!PersonalSetting.url_front.equals(""))){
            Glide.with(this)
                    .load(Config.URL+PersonalSetting.url_back)
                    .asBitmap()
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(iv_back);
        }
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_owner_insure;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ownerinsure_ib_back:
                finish();
                break;
            case R.id.ownerinsure_iv_identityBack:
                state=1;
                new MaterialDialog.Builder(this)
                        .title("选择图片")
                        .items(R.array.pickHead)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                switch (which){
                                    case 0://相机拍摄
                                        capture();
                                        break;
                                    case 1://相册选取
                                        album();
                                        break;
                                }
                            }
                        }).show();
                break;
            case R.id.ownerinsure_iv_identityFront:
                state=0;
                new MaterialDialog.Builder(this)
                        .title("选择图片")
                        .items(R.array.pickHead)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                switch (which){
                                    case 0://相机拍摄
                                        capture();
                                        break;
                                    case 1://相册选取
                                        album();
                                        break;
                                }
                            }
                        }).show();
                break;
            case R.id.ownerinsure_tv_submit:
                dialog.setMessage("更新身份证...");
                dialog.show();
                String idcard=et_identity.getText().toString().trim();
                if(idcard.equals("")){
                    return;
                }
                HashMap<String,String> hashMap=new HashMap<>();
                hashMap.put("UserPhone",user.getUserPhone());
                hashMap.put("UserPassword",user.getUserPwd());
                hashMap.put("IDCard",idcard);
                okHttp.httpInfoPost(Config.URL+Config.UPDATE_IDCARD,Config.translateMap(hashMap),callback,0);
                break;
        }
    }

    //相机拍摄处理
    private void album() {
        Intent intent=new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        if(intent.resolveActivity(getPackageManager())!=null){
            startActivityForResult(intent,GALLERY_IMAGE);
        }
    }

    //相册选取照片处理
    private void capture() {
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getPackageManager())!=null){
            File file=createFile();
            if(file!=null){
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent,CAPTURE_IMAGE);
            }
        }else{
            Toast.makeText(this,"无法启动相机",Toast.LENGTH_SHORT).show();
        }
    }

    private String mCurrentPath;
    private File createFile() {
        File file=new File(getExternalCacheDir(),"identity.jpeg");
        if(file.exists()){
            file.delete();
        }
        mCurrentPath=file.getAbsolutePath();
        return file;
    }
    private String mFilePath;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==RESULT_OK){
            String filePath=null;
            if(requestCode==CAPTURE_IMAGE){
                if(mCurrentPath!=null){
                    filePath=mCurrentPath;
                }
            }else if(requestCode==GALLERY_IMAGE){
                filePath=getPath(data.getData());
            }
            if(!TextUtils.isEmpty(filePath)){
                mFilePath=filePath;
                if(state==0) {
                    dialog.setMessage("正在上传身份证正面");
                }else{
                    dialog.setMessage("正在上传身份证反面");
                }
                dialog.show();
                new Thread(){
                    @Override
                    public void run() {
                        HashMap<String,String> hashMap=new HashMap();
                        hashMap.put("UserPhone",user.getUserPhone());
                        hashMap.put("UserPassword",user.getUserPwd());
                        if(state==0){
                            hashMap.put("ZF","z");
                        }else{
                            hashMap.put("ZF","f");
                        }
                        FileImageUpload.uploadFile(new File(mFilePath), "File", Config.translateMap(hashMap), Config.URL + Config.UPDATE_IDCARDIMAGE, imageCallback); //上传头像
                    }
                }.start();
            }
        }
    }
    private String getPath(Uri data) {
        String filePath=null;
        String[] ff=new String[]{MediaStore.MediaColumns.DATA};
        Cursor cursor=getContentResolver().query(data,ff,null,null,null);
        if(cursor==null){
            return null;
        }
        cursor.moveToFirst();
        filePath=cursor.getString(cursor.getColumnIndex(ff[0]));
        cursor.close();
        return filePath;
    }
}
